package com.yifi.system.controller;

import java.util.HashMap;
import java.util.Map;

import com.jfinal.aop.Inject;
import com.jfinal.core.Path;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.yifi.common.SysUtil;
import com.yifi.common.URLCodeUtils;
import com.yifi.common.base.BaseController;
import com.yifi.common.utils.StringUtils;
import com.yifi.system.service.OnLineServcie;

/**
 * 2020-04-13
 * @author yao
 * 在线用户实现
 * 强退无用用户
 */
@Path(value="/sys_user_online",viewPath = "/")
public class sys_user_online_controller extends BaseController {

	public void index()
	{
		String localsession = getSession().getId();
		setAttr("localsession", localsession);
		render("system/sys_user_online.html");
	}
	
	public void list()
	{
		String sql = "delete from sys_user_online t1"
				+ " where last_access_time<(sysdate - 5/24/60)";//大于5分钟的自动取消登录，登录失效
		Db.update(sql);
		
		int page = getParaToInt("page", 1);
		int rows = getParaToInt("rows", 20);
		String usernum=getPara("usernum","");
		usernum=URLCodeUtils.decode(usernum);
		String sqlSelect="select t1.* ";
		String sqlExcept="from sys_user_online t1 where 1=1";
		if(StringUtils.isNotEmpty(usernum))
		{
			sqlExcept+=" and t1.login_name like '%"+usernum+"%' ";
		}
		sqlExcept+=" order by t1.last_access_time desc";
		Page<Record> pageR = Db.paginate(page, rows, sqlSelect, sqlExcept);
		
		Map<String, Object> mapdata = new HashMap<String, Object>();
		mapdata.put("total", pageR.getTotalRow());
		mapdata.put("rows", pageR.getList());
		renderJson(mapdata);
	}
	
	//强退用户

	
	@Inject
	private OnLineServcie onlineService;
	
	public void unline()
	{
		String sessionid=getPara("sessionid","");
		String login_name=getPara("login_name","");
		String local = getSession().getId();
		//不能强退自己session
		if(local.equals(sessionid))
		{
			renderJson(SysUtil.ResultMsg(false, "不能强制下线当前用户！"));return;
		}
		String gs_user=getSessionAttr("Gs_uid");
		//一般用户不能强退admin
		if(login_name.equals("admin")&&!gs_user.equals("admin"))
		{
			renderJson(SysUtil.ResultMsg(false, "只用admin强制下线admin用户！"));return;
		}
		
		if(onlineService.unlineUser(sessionid))
		{
			renderJson(SysUtil.ResultMsg(true, "下线成功！"));
		}
		else
		{
			renderJson(SysUtil.ResultMsg(false, "下线失败！"));
		}
	}
}
